package com.example.wechat;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wechat.adapter.MessageAdapter;
import com.example.wechat.database.WeChatDatabaseManager;
import com.example.wechat.model.Message;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PrivateChatActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton btnBack;
    private ImageButton btnMore;
    private TextView chatTitle;
    private TextView onlineStatus;
    private RecyclerView messageList;
    private EditText inputMessage;
    private Button btnSend;
    private ImageButton btnVoice;
    private ImageButton btnEmoji;
    private ImageButton btnImage;
    
    private WeChatDatabaseManager dbManager;
    private int currentUserId = 1; // 假设当前用户ID为1
    private int friendId; // 聊天对象的ID
    private String friendName; // 聊天对象的名称
    private List<Message> messages;
    private MessageAdapter messageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_private_chat);

        // 获取传递的好友信息
        friendId = getIntent().getIntExtra("friend_id", 2);
        friendName = getIntent().getStringExtra("friend_name");

        // 初始化数据库
        dbManager = new WeChatDatabaseManager(this);
        dbManager.open();

        // 初始化视图
        initViews();
        // 设置点击事件
        setClickListeners();
        // 加载聊天记录
        loadMessages();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        btnMore = findViewById(R.id.btn_more);
        chatTitle = findViewById(R.id.chat_title);
        onlineStatus = findViewById(R.id.online_status);
        messageList = findViewById(R.id.message_list);
        inputMessage = findViewById(R.id.input_message);
        btnSend = findViewById(R.id.btn_send);
        btnVoice = findViewById(R.id.btn_voice);
        btnEmoji = findViewById(R.id.btn_emoji);
        btnImage = findViewById(R.id.btn_image);

        chatTitle.setText(friendName);
        
        // 设置RecyclerView
        messageList.setLayoutManager(new LinearLayoutManager(this));
        messages = new ArrayList<>();
        messageAdapter = new MessageAdapter(this, messages);
        messageList.setAdapter(messageAdapter);
    }

    private void setClickListeners() {
        btnBack.setOnClickListener(this);
        btnMore.setOnClickListener(this);
        btnSend.setOnClickListener(this);
        btnVoice.setOnClickListener(this);
        btnEmoji.setOnClickListener(this);
        btnImage.setOnClickListener(this);
    }

    private void loadMessages() {
        // 从数据库加载聊天记录
        List<String> historyMessages = dbManager.getMessages(currentUserId, friendId);
        messages.clear();
        
        // 将数据库中的消息转换为Message对象
        for (String msg : historyMessages) {
            String[] parts = msg.split("：");
            if (parts.length > 1) {
                String sender = parts[0];
                String content = parts[1];
                boolean isFromMe = sender.equals("我");
                messages.add(new Message(
                    messages.size(),
                    isFromMe ? currentUserId : friendId,
                    isFromMe ? friendId : currentUserId,
                    content,
                    new Date(),
                    isFromMe,
                    isFromMe ? "我" : friendName
                ));
            }
        }
        
        messageAdapter.notifyDataSetChanged();
        scrollToBottom();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_back) {
            finish();
        } else if (id == R.id.btn_more) {
            showMoreOptions();
        } else if (id == R.id.btn_send) {
            sendMessage();
        } else if (id == R.id.btn_voice) {
            startVoiceRecord();
        } else if (id == R.id.btn_emoji) {
            showEmojiPanel();
        } else if (id == R.id.btn_image) {
            selectImage();
        }
    }

    private void showMoreOptions() {
        // TODO: 实现更多选项菜单
        Toast.makeText(this, "更多功能", Toast.LENGTH_SHORT).show();
    }

    private void startVoiceRecord() {
        // TODO: 实现语音录制功能
        Toast.makeText(this, "语音功能", Toast.LENGTH_SHORT).show();
    }

    private void showEmojiPanel() {
        // TODO: 实现表情面板
        Toast.makeText(this, "表情功能", Toast.LENGTH_SHORT).show();
    }

    private void selectImage() {
        // TODO: 实现图片选择功能
        Toast.makeText(this, "图片功能", Toast.LENGTH_SHORT).show();
    }

    private void sendMessage() {
        String content = inputMessage.getText().toString().trim();
        if (content.isEmpty()) {
            Toast.makeText(this, "请输入消息内容", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存消息到数据库
        long result = dbManager.addMessage(currentUserId, friendId, content, 0);
        if (result != -1) {
            // 创建新消息对象
            Message newMessage = new Message(
                messages.size(),
                currentUserId,
                friendId,
                content,
                new Date(),
                true,
                "我"
            );
            
            // 添加到消息列表
            messages.add(newMessage);
            messageAdapter.notifyDataSetChanged();
            
            // 清空输入框
            inputMessage.setText("");
            // 滚动到底部
            scrollToBottom();
        } else {
            Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void scrollToBottom() {
        messageList.post(() -> {
            if (messages.size() > 0) {
                messageList.smoothScrollToPosition(messages.size() - 1);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbManager != null) {
            dbManager.close();
        }
    }
} 